package com.kanshu.ksgb.fastread.doudou.module.download.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.StringUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.BookBussinessService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.ReaderJumpConfig;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.module.download.adapter.SimpleTreeAdapter;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.DownLoadChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.MakeMoneyBean;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DownloadProgressEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.retrofit.DownloadChapterPresenter;
import com.kanshu.ksgb.fastread.doudou.module.download.service.DownloadBookService;
import com.kanshu.ksgb.fastread.doudou.module.download.utils.DownLoadHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xubo on 2018/11/23
 */

@SuppressLint("SetTextI18n")
@Route(path = ARouterConfig.DOWNLOAD_DOWNLOAD_CHAPTER)
public class DownLoadChapterActivity extends BaseActivity implements INetCommCallback<List<DownLoadChapterBean>>, SimpleTreeAdapter.onSelectChapterListener {

    private static final int DOWNLOAD_STATE_NOT_SELECT = 0;   // 初始状态，未选择章节
    private static final int DOWNLOAD_STATE_HAS_SELECT = 1;    // 已选择章节，等待用户点击下载
    private static final int DOWNLOAD_STATE_ONGOING = 2;       // 下载中，刷新页面更新进度
    private static final int DOWNLOAD_STATE_FINISH = 3;        // 下载完成，重新下载/开始阅读

    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.list_container)
    ListView mListContainer;
    @BindView(R.id.download_container)
    LinearLayout mDownloadContainer;
    @BindView(R.id.ad_container)
    FrameLayout mAdContainer;
    @BindView(R.id.select_chapter_count)
    TextView mTvSelectChapteCount;
    @BindView(R.id.beans_count)
    TextView mTvBeansCount;
    @BindView(R.id.download_book_state)
    TextView mTvDownloadState;
    @BindView(R.id.download_progress)
    TextView mTvDownloadProgress;
    @BindView(R.id.download_seekbar)
    SeekBar mDownloadSeekbar;
    @BindView(R.id.download_fail_message)
    TextView mTvFailMessage;
    @BindView(R.id.submit_download)
    TextView mTvSubmitDownload;

    TextView mTvRight;

    DownloadChapterPresenter mPresenter = new DownloadChapterPresenter(lifeCyclerSubject);

    private String mBookId;
    private SimpleTreeAdapter mAdapter;
    List<DownLoadChapterBean> mChapterList = new ArrayList<>();
    // 剩余金豆
    private int mRemainingBeans;
    // 已下载章节数
    private int mHasDownloadCount;
    // 选中下载章节数
    private int mSelectCount;
    // 选中下载金豆数
    private int mBeansCount;
    // 书籍下载状态
    private int mBookDownloadState = DOWNLOAD_STATE_NOT_SELECT;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_chapter);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        setTitle("批量下载");
        initData();
    }

    private void initData(){
        mBookId = getIntent().getStringExtra("book_id");
        String loginBeans = MMKVUserManager.getInstance().getLoginBeans();
        mRemainingBeans = Integer.valueOf(loginBeans);
        mDownloadSeekbar.setOnTouchListener((v, event) -> true);
        mAdapter = new SimpleTreeAdapter(mListContainer, this, mChapterList);
        mAdapter.setSelectChapterListener(this);
        mPresenter.getDownloadChapter(mBookId, this);
        mListContainer.setAdapter(mAdapter);

        initBtnRight();
        if(DownloadBookService.isBookIdDownload(mBookId)){
            mBookDownloadState = DOWNLOAD_STATE_ONGOING;
            int[] progress = DownloadBookService.getCurrentProgress(mBookId);
            if(progress[0] > 0 && progress[1] > 0) {
                mHasDownloadCount = progress[0];
                mSelectCount = progress[1];
            }
        }
        initBookDownloadState();

        mTvSelectChapteCount.setText(StringUtils.getString(R.string.select_chapter_count, mSelectCount));
        mTvBeansCount.setText(StringUtils.getString(R.string.beans_count, mBeansCount, mRemainingBeans));

    }

    /**
     * 初始化广告
     */
    private void initAd(){
        AdUtils.fetchAdUtil(this, mAdContainer, null, ADConfigBean.POSITION_DOWNLOAD_BANNER, AdStyleBean.BANNER_STYLE, 0, new BaseAdListener() {
            @Override
            public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
                DisplayUtils.visible(mAdContainer);
            }

            @Override
            public void onAdLoadFailed() {
                DisplayUtils.gone(mAdContainer);
            }

            @Override
            public void onAdClicked() {

            }

            @Override
            public void onADClosed() {

            }

            @Override
            public void onBackAd(@NotNull Object ad) {

            }
        });
    }

    /**
     * 添加全选按钮
     */
    private void initBtnRight() {
        mTvRight = new TextView(getActivity());
        mTvRight.setText("全选");
        mTvRight.setGravity(Gravity.CENTER);
        mTvRight.setTextColor(Color.parseColor("#333333"));
        mTvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.dip2px(this, 15));
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL;
        mTitle.getRightContainer().addView(mTvRight, params);
        mTitle.getRightContainer().setVisibility(View.VISIBLE);
        mTvRight.setPadding(DisplayUtils.dip2px(this, 6), DisplayUtils.dip2px(this, 6), DisplayUtils.dip2px(this, 6), DisplayUtils.dip2px(this, 6));
        mTvRight.setOnClickListener(v -> {
            if(mAdapter.getIsEdit()) {
                mAdapter.setSelectAllState(!mTvRight.getText().toString().startsWith("取消"));
                mTvRight.setText(mTvRight.getText().toString().startsWith("取消") ? "全选" : "取消全选");
            }
        });
    }

    private void initBookDownloadState(){
        mTvSubmitDownload.setEnabled(true);
        mTvRight.setEnabled(false);
        mAdapter.setIsEdit(true);
        mTvRight.setTextColor(Color.parseColor("#999999"));
        switch (mBookDownloadState){
            case DOWNLOAD_STATE_NOT_SELECT: // 初始状态，可选择章节进行下载
                mTvSubmitDownload.setEnabled(false);
                mTvRight.setEnabled(true);
                mTvRight.setTextColor(Color.parseColor("#333333"));
                mTvSubmitDownload.setText("请选择要下载的章节");
                mTvSubmitDownload.setBackgroundResource(R.mipmap.ic_btn_no_select_bg);
                mTvSubmitDownload.setTextColor(getResources().getColor(R.color.color_b8b8b8));
                break;
            case DOWNLOAD_STATE_HAS_SELECT: // 已选择章节，等待用户点击下载
                mTvRight.setEnabled(true);
                mTvRight.setTextColor(Color.parseColor("#333333"));
                mTvSubmitDownload.setBackgroundResource(R.mipmap.ic_btn_phone_login_bg);
                mTvSubmitDownload.setTextColor(getResources().getColor(R.color.menu_txt_normal));
                if(mBeansCount <= mRemainingBeans){
                    mTvSubmitDownload.setText("开始下载");
                }else{
                    mTvSubmitDownload.setText("金豆不足，快去赚钱吧！");
                }
                break;
            case DOWNLOAD_STATE_ONGOING: // 下载中，刷新页面更新进度
                mAdapter.setIsEdit(false);
                DisplayUtils.gone(mTvSelectChapteCount, mTvBeansCount, mTvFailMessage);
                DisplayUtils.visible(mTvDownloadState, mTvDownloadProgress, mDownloadSeekbar);
                int progress = (mHasDownloadCount == 0 || mSelectCount == 0) ? 0 : mHasDownloadCount * 100 / mSelectCount;
                mDownloadSeekbar.setProgress(progress);
                mTvDownloadProgress.setText(progress + "%");
                mTvSubmitDownload.setText("后台下载");
                mTvSubmitDownload.setBackgroundResource(R.mipmap.ic_btn_phone_login_bg);
                mTvSubmitDownload.setTextColor(getResources().getColor(R.color.menu_txt_normal));
                break;
            case DOWNLOAD_STATE_FINISH: // 下载完成，重新下载/开始阅读
                mAdapter.setIsEdit(false);
                String failChapter = MMKVUserManager.getInstance().getDownLoadFailGroupId(mBookId);
                if(failChapter.length() < Constants.DOWNLOAD_FAILINFO_DEFAULT_LENGTH){ // 无下载失败章节
                    DisplayUtils.gone(mTvFailMessage);
                    DisplayUtils.visible(mDownloadSeekbar);
                    mTvSubmitDownload.setText("开始阅读");
                    mTvDownloadState.setText("下载成功");
                }else{
                    DisplayUtils.gone( mTvDownloadProgress, mDownloadSeekbar);
                    DisplayUtils.visible(mTvFailMessage);
                    mTvFailMessage.setText(MMKVUserManager.getInstance().getDownLoadFailBecause(mBookId));
                    mTvSubmitDownload.setText("重新下载");
                    mTvDownloadState.setText("下载失败");
                }
                break;
        }
    }

    /**
     * 准备下载  先进行扣费
     */
    private void prepareDownLoad(){
        // 设置adapter不可点击
        mAdapter.setIsEdit(false);
        StringBuilder chapter_ids = new StringBuilder();
        mChapterList = mAdapter.getData();

        for (DownLoadChapterBean parentBean : mChapterList) {
            if(!parentBean.is_canceldownload){
                continue;
            }
            for (DownLoadChapterBean childBean : parentBean.chapters) {
                if(parentBean.is_download || childBean.is_download){
                    chapter_ids.append(childBean.content_id).append(",");
                }
            }
        }

        showLoading("");
        mPresenter.downloadMake(mBookId, chapter_ids.toString(), new INetCommCallback<BaseResult<MakeMoneyBean>>() {
            @Override
            public void onResponse(BaseResult<MakeMoneyBean> response) {
                if(response != null && response.result != null && response.result.status != null){
                    if(response.result.status.code == 0) {
                        // 扣费成功 开始下载
                        mBookDownloadState = DOWNLOAD_STATE_ONGOING;
                        initBookDownloadState();
                        startDownload();
                        MMKVUserManager.getInstance().setLoginBeans(mRemainingBeans - (response.result.data == null ? 0 : response.result.data.beans) + "");
                        // 下载书籍 自动加入书架
                        ARouter.getInstance().navigation(BookBussinessService.class).addToShelf(mBookId);
                    }else{
                        ToastUtil.showStaticMessage(response.result.status.msg);
                    }
                } else {
                    ToastUtil.showStaticMessage("扣费失败，请稍候再试！");
                    // 设置adapter可点击
                    mAdapter.setIsEdit(true);
                }
                dismissLoading();
            }

            @Override
            public void onError(int code, String errDesc) {
                ToastUtil.showStaticMessage(errDesc);
                // 设置adapter可点击
                mAdapter.setIsEdit(true);
                dismissLoading();
            }
        });
    }

    /**
     * 开始下载
     */
    private void startDownload(){
        DownloadBookService.reSetCurrentProgress(mBookId);
        for (DownLoadChapterBean parentBean : mChapterList) {
            if(!parentBean.is_canceldownload){
                continue;
            }
            DownLoadChapterBean selectBean = new DownLoadChapterBean();
            selectBean.id = parentBean.id;
            selectBean.book_id = mBookId;
            selectBean.book_title = parentBean.book_title;
            selectBean.group_beans = parentBean.group_beans;
            selectBean.title = parentBean.title;
            selectBean.chapters = new ArrayList<>();
            for (DownLoadChapterBean childBean : parentBean.chapters) {
                if(childBean.is_download || parentBean.is_download){
                    childBean.beans = 0;
                    selectBean.chapters.add(childBean);
                }
            }
            if(selectBean.chapters.size() > 0){
                DownloadBookService.checkServiceAndPostEvent(this, selectBean);
            }
        }
    }

    @OnClick({R.id.submit_download})
    public void onClicked(View view){
        switch (view.getId()){
            case R.id.submit_download:
                switch (mBookDownloadState){
                    case DOWNLOAD_STATE_NOT_SELECT: // 初始状态，不可点击
                        break;
                    case DOWNLOAD_STATE_HAS_SELECT: // 已选择章节，点击开始下载
                        if(mRemainingBeans < mBeansCount){ // 余额不足 跳转至赚钱
                            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_MAKE_MONEY));
                        }else{
                            prepareDownLoad();
                        }
                        break;
                    case DOWNLOAD_STATE_ONGOING: // 下载中，后台下载 点击返回
                        finish();
                        break;
                    case DOWNLOAD_STATE_FINISH: // 下载完成，重新下载/开始阅读
                        String failChapter = MMKVUserManager.getInstance().getDownLoadFailGroupId(mBookId);
                        if(failChapter.length() < Constants.DOWNLOAD_FAILINFO_DEFAULT_LENGTH){ // 无下载失败章节 点击开始阅读
                            ReaderInputParams params = new ReaderInputParams();
                            params.book_id = mBookId;
                            params.continue_read = true;
                            ReaderJumpConfig.startReaderActivity(getActivity(), params);
                            finish();
                        } else {    // 有失败章节，点击重新下载
                            mHasDownloadCount = 0;
                            mBookDownloadState = DOWNLOAD_STATE_ONGOING;
                            mSelectCount = 10; // 默认设置重新下载的为10章节
                            initBookDownloadState();
                            mSelectCount = DownLoadHelper.againDownload(this, mBookId);
                        }
                        break;
                }
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDownloadProgressMessage(DownloadProgressEvent event) {
        if(!event.isGroupFinish && TextUtils.equals(event.bookId, mBookId) && mBookDownloadState == DOWNLOAD_STATE_ONGOING){ // 下载中 更新进度
            mAdapter.notifyDataSetChanged();
            mHasDownloadCount += 1;
            int progress = mSelectCount == 0 ? 0 : mHasDownloadCount * 100 / mSelectCount;
            mDownloadSeekbar.setProgress(progress);
            mTvDownloadProgress.setText(progress + "%");
        } else if(event.isGroupFinish && TextUtils.equals(event.bookId, mBookId)) { // 组任务完成 刷新页面
            mAdapter.notifyDataSetChanged();
            if(mHasDownloadCount >= mSelectCount || !DownloadBookService.isBookIdDownload(mBookId)){ // 下载完成
                mDownloadSeekbar.setProgress(100);
                mTvDownloadProgress.setText(100 + "%");
                mBookDownloadState = DOWNLOAD_STATE_FINISH;
                initBookDownloadState();
            }
        }
    }

    @Override
    public void selectChapterListener(int chapterCount, int beansCount) {
        mSelectCount = chapterCount;
        mBeansCount = beansCount;
        mTvSelectChapteCount.setText(StringUtils.getString(R.string.select_chapter_count, chapterCount));
        mTvBeansCount.setText(StringUtils.getString(R.string.beans_count, beansCount, mRemainingBeans));
        mBookDownloadState = chapterCount > 0 ? DOWNLOAD_STATE_HAS_SELECT : DOWNLOAD_STATE_NOT_SELECT;
        initBookDownloadState();
    }

    public static void actionStart(Context context, String bookId){
        Intent intent = new Intent(context, DownLoadChapterActivity.class);
        intent.putExtra("book_id", bookId);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResponse(List<DownLoadChapterBean> loadChapterBeanList) {
        if(!Utils.isEmptyList(loadChapterBeanList)){
            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_HIDE);
            DisplayUtils.visible(mListContainer, mDownloadContainer, mAdContainer);
            mAdapter.setData(loadChapterBeanList);
            initAd();
        }else{
            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
        }
    }

    @Override
    public void onError(int code, String errDesc) {
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
    }
}
